package com.steve.combat.thread.多线程交替打印ABC;

import java.util.concurrent.Semaphore;

/**
 * @Author: STEVE
 * @Description: 使用信号量
 * @since: 2025-06-01
 */
public class PrintABCUsingSemaphore {

    /**
     * 实现步骤
     * 定义三个信号量semA、semB、semC。
     * 每个线程在自己的信号量上等待，打印完成后释放下一个线程的信号量。
     */

    private final Semaphore semA = new Semaphore(1);
    private final Semaphore semB = new Semaphore(0);
    private final Semaphore semC = new Semaphore(0);

    public static void main(String[] args) {
        PrintABCUsingSemaphore task = new PrintABCUsingSemaphore();

        Thread threadA = new Thread(task::printA);
        Thread threadB = new Thread(task::printB);
        Thread threadC = new Thread(task::printC);

        threadA.start();
        threadB.start();
        threadC.start();
    }

    public void printA() {
        try {
            for (int i = 0; i < 10; i++) {
                semA.acquire();
                System.out.print("A");
                semB.release();
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public void printB() {
        try {
            for (int i = 0; i < 10; i++) {
                semB.acquire();
                System.out.print("B");
                semC.release();
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public void printC() {
        try {
            for (int i = 0; i < 10; i++) {
                semC.acquire();
                System.out.print("C");
                semA.release();
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

}
